//
//  DDCreateOrderViewController.m
//  Dingdong
//
//  Created by 程强 on 16/11/15.
//  Copyright © 2016年 程强. All rights reserved.
//

#import "DDCreateOrderViewController.h"
#import "DDSelectAddressViewController.h"
#import "DDCreateOrderResultViewController.h"
#import "DDReceiptAddSet.h"
#import "DDCreateOrderTableCell.h"
#import "DDCreateOrderCellSectionFooter.h"
#import "DDOrderManager.h"
#import "DDCouponViewController.h"
#import "DDPrepareOrderSet.h"

typedef NS_ENUM(NSInteger, ValidateOrderType) {
    ValidateOrderTypeNormal = 0,
    ValidateOrderTypeUpdate,
};

@interface DDCreateOrderViewController ()<UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollHeight;
@property (weak, nonatomic) IBOutlet UIView *addressView;
@property (weak, nonatomic) IBOutlet UILabel *receiverNameLbl;
@property (weak, nonatomic) IBOutlet UILabel *receiverAddressLbl;
@property (weak, nonatomic) IBOutlet UIView *noAddressView;
@property (weak, nonatomic) IBOutlet UITableView *goodsTable;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *goodsTableHeight;
@property (weak, nonatomic) IBOutlet UILabel *orderAmountLbl;
@property (weak, nonatomic) IBOutlet UILabel *selectDistributionLbl;
@property (weak, nonatomic) IBOutlet UIView *botView;
@property (strong, nonatomic) DDReceiptAddObj *selectedReceiptAdd;
@property (strong, nonatomic) DDOrderManager *manager;
@property (strong, nonatomic) DDPrepareOrderSet *prepareSet;/**<数据源*/
@property (weak, nonatomic) IBOutlet UITextField *remarkTxf;
@property (strong, nonatomic) NSString *selectDistributionTime;
@property (strong, nonatomic) NSMutableDictionary *selectedCouponDic;
@end

@implementation DDCreateOrderViewController
- (void)gotoBack
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [DDOrderManager new];
    [self layoutCreateOrderView];
}
- (void)layoutCreateOrderView
{
    //获取默认收货地址
    [self getDefaultAddress];
    self.scrollWidth.constant = ScreenWidth;
    self.scrollHeight.constant = 2000;
    self.selectDistributionTime = @"Any time";
    self.selectedCouponDic = [[NSMutableDictionary alloc]initWithCapacity:0];
    self.botView.layer.shadowOffset = CGSizeMake(0, 2);
    self.botView.layer.shadowOpacity = 0.80;
    self.botView.layer.shadowColor = [UIColor darkGrayColor].CGColor;
}

#pragma mark --- IBAction
- (IBAction)addReceiptAddressClick:(id)sender
{
    DDSelectAddressViewController *vc = StoryBoardViewController(@"Order", @"DDSelectAddressViewController");
    [self.navigationController pushViewController:vc animated:YES];
    [vc userSelectAddressHandler:^(DDReceiptAddObj *obj) {
        self.selectedReceiptAdd = obj;
        [self reloadSelectedAddressInfo];
        [self prepareForCommitOrderWithType:ValidateOrderTypeUpdate];
    }];
}
- (IBAction)choseAddressClick:(id)sender
{
    DDSelectAddressViewController *vc = StoryBoardViewController(@"Order", @"DDSelectAddressViewController");
    [self.navigationController pushViewController:vc animated:YES];
    [vc userSelectAddressHandler:^(DDReceiptAddObj *obj) {
        self.selectedReceiptAdd = obj;
        [self reloadSelectedAddressInfo];
        [self prepareForCommitOrderWithType:ValidateOrderTypeUpdate];
    }];
}
- (IBAction)payClick:(id)sender
{
    weak_Self(self);
    [self createOrderSuccess:^{
        DDCreateOrderResultViewController *vc = StoryBoardViewController(@"Order", @"DDCreateOrderResultViewController");
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
}
- (void)reloadSelectedAddressInfo
{
    self.addressView.hidden = NO;
    self.noAddressView.hidden = YES;
    self.receiverNameLbl.text = self.selectedReceiptAdd.name;
    self.receiverAddressLbl.text = FormatString(@"%@,%@,%@,%@", self.selectedReceiptAdd.addr,self.selectedReceiptAdd.region,self.selectedReceiptAdd.city,self.selectedReceiptAdd.province);
}
- (IBAction)distributionTimeClick:(id)sender
{
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"Choose distribution time" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Any time" otherButtonTitles:@"Only working days",@"Only a day off", nil];
    [sheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        self.selectDistributionTime = @"Any time";
    }else if (buttonIndex == 1){
        self.selectDistributionTime = @"Only working days";
    }else if (buttonIndex == 2){
        self.selectDistributionTime = @"Only a day off";
    }
    self.selectDistributionLbl.text = self.selectDistributionTime;
}
#pragma mark --- UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.prepareSet.storeAry.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    DDPrepareOrderObj *obj = self.prepareSet.storeAry[section];
    return obj.goodslist.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    DDPrepareOrderObj *obj = self.prepareSet.storeAry[section];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
    view.backgroundColor = [UIColor whiteColor];
    CGFloat width = [ToolKit widthWithFont:[UIFont systemFontOfSize:15.0] height:30 text:obj.store_name];
    width+=10;
    if (width>ScreenWidth/2.0) {
        width = ScreenWidth/2.0;
    }
    KKLabel *titleLbl = [[KKLabel alloc]initWithBlock:^(KKLabel *lbl) {
        lbl.laText(@"",RGBColor(100, 100, 100),[UIFont systemFontOfSize:15.0],NSTextAlignmentLeft);
    }];
    [view addSubview:titleLbl];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(view);
        make.left.equalTo(view).offset(15);
        make.height.equalTo(@30);
        make.width.equalTo(@(width));
    }];
    titleLbl.text = obj.store_name;
    
    KKLabel *activityLbl = [[KKLabel alloc]initWithBlock:^(KKLabel *lbl) {
        lbl.laText(@"",RGBColor(255, 80, 80),[UIFont systemFontOfSize:15.0],NSTextAlignmentLeft);
    }];
    [view addSubview:activityLbl];
    [activityLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(view);
        make.left.equalTo(titleLbl.mas_right).offset(15);
        make.right.equalTo(view).offset(-20);
        make.height.equalTo(@30);
    }];
    activityLbl.text = obj.activity_name;
    
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    DDPrepareOrderObj *obj = self.prepareSet.storeAry[section];
    if (obj.storeprice.gift_id.integerValue == 0) {
        return 213;
    }else{
        return 264.0;
    }
    return 213.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    DDPrepareOrderObj *obj = self.prepareSet.storeAry[section];
    DDCreateOrderCellSectionFooter *footer = [[DDCreateOrderCellSectionFooter alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 101)];
    if (obj.hasBonus.integerValue == 1) {
        if (obj.bonusList.count>0) {
            DDCouponObj *coupon = obj.bonusList[0];
            footer.couponLbl.text = coupon.type_name;
        }else
            footer.couponLbl.text = @"One valid coupon";
    }else{
        footer.couponLbl.text = @"None";
    }
    footer.totalMoney = FormatString(@"$%@", obj.storeprice.orderPrice);
    footer.shippingPrice = FormatString(@"$%@", obj.storeprice.shippingPrice);
    footer.discount = FormatString(@"%@", obj.storeprice.discountPrice);
    footer.goodsNum = obj.goodslist.count;
    if (obj.shiplist.count>0) {
        DDPrepareOrderShipObj *deliveryObj = obj.shiplist[0];
        footer.delivery = FormatString(@"%@ $%@", deliveryObj.name,obj.storeprice.shippingPrice);
    }
    
    [footer userChoseValidCouponClick:^{
        DDCouponViewController *vc = StoryBoardViewController(@"Coupon", @"DDCouponViewController");
        NSDictionary *dic = @{@"store_id":obj.store_id,@"store_price":obj.storeprice.orderPrice};
        vc.couponType = DingDongShowCouponTypeStore;
        vc.storeInfo = dic;
        [self.navigationController pushViewController:vc animated:YES];
        [vc userSelectCouponHandler:^(DDCouponObj *coupon) {
           footer.couponLbl.text = coupon.type_name;
            if (!obj.bonusList) {
                obj.bonusList = [[NSMutableArray alloc]initWithCapacity:0];
            }else{
                [obj.bonusList removeAllObjects];
            }
            [obj.bonusList addObject:coupon];

            CGFloat nowOrderPrice = [obj.storeprice.orderPrice doubleValue]-[coupon.type_money doubleValue];
            obj.storeprice.orderPrice = @(nowOrderPrice);
            [tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
            [self.selectedCouponDic setObject:coupon forKey:FormatString(@"%@", obj.store_id)];
        }];
        
    }];
    if (obj.storeprice.gift_id.integerValue == 0) {
        footer.hasGift = NO;
    }else{
        footer.hasGift = YES;
        [self getStoreGift:obj.storeprice.gift_id success:^(DDPrepareOrderGift *gift){
            obj.giftObj = gift;
            footer.giftIconUrl = obj.giftObj.gift_img;
            footer.giftName = obj.giftObj.gift_name;
            [tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
        }];
    }
    
    return footer;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *indentifier = @"CreateCell";
    
    DDCreateOrderTableCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
    
    if (!cell) {
        cell = [[DDCreateOrderTableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    DDPrepareOrderObj *obj = self.prepareSet.storeAry[indexPath.section];
    DDPrepareOrderGoodsObj *goods = obj.goodslist[indexPath.row];
    [cell.goodsIcon sd_setImageWithURL:[NSURL URLWithString:goods.image_default] placeholderImage:nil];
    cell.goodsNameLbl.text = goods.name;
    cell.goodsCountLbl.text = FormatString(@"Quantity:%@", goods.num);
    cell.goodsPriceLbl.text = FormatString(@"$%@", goods.price);
    return cell;
}
#pragma mark --- 接口
- (void)prepareForCommitOrderWithType:(ValidateOrderType)type
{
    weak_Self(self);
    NSNumber *add_id = @-1;
    NSString *isCountShip = @"no";
    if (self.selectedReceiptAdd.addr_id) {
        add_id = self.selectedReceiptAdd.addr_id;
        isCountShip = @"yes";
    }
    NSString *bonus =  [ToolKit JSONEncodeObj:[NSArray new]];
    if (type == ValidateOrderTypeUpdate) {
        NSMutableArray *bonusAry = [[NSMutableArray alloc]initWithCapacity:0];
        for (NSString *key in self.selectedCouponDic.allKeys) {
            DDCouponObj *coupon = self.selectedCouponDic[key];
            NSDictionary *dic = @{@"bonusId":coupon.bonus_id};
            NSArray *dicAry = @[dic];
            NSDictionary *bigDic = @{@"store_id":key,@"bonusIdList":dicAry};
            [bonusAry addObject:bigDic];
            bonus = [ToolKit JSONEncodeObj:bonusAry];
        }
    }
    [self showHUD];
    [[self.manager prepareForCommitOrderInfo:add_id isCountShip:isCountShip bonusJson:bonus]subscribeNext:^(id x) {
        weakSelf.prepareSet = x;
        [weakSelf reloadGoodsList];
        [weakSelf.goodsTable reloadData];
        if (type == ValidateOrderTypeUpdate) {
            [weakSelf.selectedCouponDic removeAllObjects];
        }
    } error:^(NSError *error) {
        
    } completed:^{
        [weakSelf hideHUD];
    }];
}
- (void)reloadGoodsList
{
    NSInteger section = self.prepareSet.storeAry.count;
    __block NSInteger row = 0;
    __block NSInteger giftCount = 0;
    __block CGFloat allMoney = 0;/**订单总金额*/
    [self.prepareSet.storeAry enumerateObjectsUsingBlock:^(DDPrepareOrderObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSInteger cartCount =  obj.goodslist.count;
        row+=cartCount;
        
        if (obj.storeprice.gift_id.integerValue != 0) {
            giftCount+=1;
        }
        
        allMoney+=[obj.storeprice.orderPrice doubleValue];
        
    }];
    self.goodsTableHeight.constant = (44+213)*section+row*120+giftCount*51;
    self.orderAmountLbl.text = FormatString(@"$%.2f", allMoney);
    self.scrollHeight.constant = 10+75+10+self.goodsTableHeight.constant+152+10;
}
- (void)getDefaultAddress
{
    weak_Self(self);
    [[self.manager getDefaultAddress]subscribeNext:^(id x) {
        weakSelf.selectedReceiptAdd = x;
        [weakSelf reloadSelectedAddressInfo];
    } error:^(NSError *error) {
        
    } completed:^{
        [weakSelf prepareForCommitOrderWithType:ValidateOrderTypeNormal];
    }];
}
- (void)getStoreGift:(NSNumber *)gift_id success:(void(^)(DDPrepareOrderGift *gift))block
{
    [[self.manager getGiftInfo:gift_id]subscribeNext:^(id x) {
        if (block) {
            block(x);
        }
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
- (void)createOrderSuccess:(void(^)())block
{
    if (!self.selectedReceiptAdd) {
        [self showMessageHUD:@"Please choose receipt address" delayHide:1.0];
        return;
    }
    NSArray *bonus = [NSArray new];
    NSString *bonusJson = [ToolKit JSONEncodeObj:bonus];
    weak_Self(self);
    [self showHUD];
    [[self.manager createOrderWithAddress:self.selectedReceiptAdd.addr_id shipDay:self.selectDistributionTime shipTime:@" " bonusJson:bonusJson paymentId:@"1" remark:self.remarkTxf.text]subscribeNext:^(id x) {
        if (block) {
            block();
        }
        [[SystemConfig shareInstance]updateCartCountSueesss:^(NSString *count) {
            
        }];
    } error:^(NSError *error) {
        
    } completed:^{
        [weakSelf hideHUD];
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
